                              //
//  CustomLoadingView.m
//  TestLoadingView
//
//  Created by chaiyanan on 15/11/12.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CustomLoadingView.h"

@interface CustomLoadingView ()

/*
@property (nonatomic, strong) UIView *animationView;
@property (nonatomic, strong) UIImageView *animationBgView;
@property (nonatomic, strong) UIImageView *yuanview;
 */

@property (nonatomic, strong) UIImageView *animationIV;
@property (nonatomic) CGPoint orginPoint;


@end


@implementation CustomLoadingView

/*
+ (CustomLoadingView *)showHudToView:(UIView *)view
{
    return [self showHudToView:view afterDelay:-1];
}

+ (CustomLoadingView *)showHudToView:(UIView *)view afterDelay:(NSTimeInterval)timeDelay
{
    [self hideHudForView:view];
    
    if (!view)
    {
        view = [[UIApplication sharedApplication].windows lastObject];
    }
    
//    view = [[UIApplication sharedApplication].windows lastObject];
    
    NSLog(@"*************%@",NSStringFromCGRect(view.bounds));
    
    for (id obj in view.subviews)
    {
        if ([obj isKindOfClass:[UITableView class]])
        {
            UITableView *tableView = (UITableView *)obj;
            if (tableView.contentInset.top>10)
            {
                return nil;
            }
            else
            {
                if (tableView.contentInset.bottom > 10)
                {
                    if (tableView.contentOffset.y>0)
                    {
                        return nil;
                    }
                    else
                    {
                        
                    }
                }
                else
                {
                    //                    return nil;
                }
            }
        }
    }
    
    CustomLoadingView *hud = [[CustomLoadingView alloc]initWithFrame:view.bounds];
    hud.backgroundColor = [UIColor clearColor];
    [view addSubview:hud];
    [view bringSubviewToFront:hud];
    
    UIImage *zhuanquan = [UIImage imageNamed:@"底"];
    hud.animationBgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, zhuanquan.size.width, zhuanquan.size.height)];
    hud.animationBgView.image = zhuanquan;
    
    
    UIImage *yuan = [UIImage imageNamed:@"圆"];
    hud.yuanview = [[UIImageView alloc]initWithFrame:CGRectMake(hud.animationBgView.frame.size.width/2 - yuan.size.width/2, hud.animationBgView.frame.size.height/2 - yuan.size.height/2, yuan.size.width, yuan.size.height)];
    hud.yuanview.image = yuan;
    [hud.animationBgView addSubview:hud.yuanview];
    
    hud.animationBgView.center = hud.center;
//    if (view != [[UIApplication sharedApplication].windows lastObject])
//    {
//        
//    }
    
    NSLog(@"[UIApplication sharedApplication].keyWindow:%@,%@",[UIApplication sharedApplication].keyWindow,NSStringFromCGRect([UIApplication sharedApplication].keyWindow.frame));
    CGPoint centerPoint = [hud convertPoint:hud.center toView:[UIApplication sharedApplication].keyWindow];
    NSLog(@"centerPoint:%@------%@",NSStringFromCGPoint(centerPoint),NSStringFromCGPoint(hud.center));
    if (centerPoint.y != [UIScreen mainScreen].bounds.size.height/2)
    {
        CGFloat plus = [UIScreen mainScreen].bounds.size.height/2 - centerPoint.y;
        CGPoint hudCenterPoint = hud.animationBgView.center;
        hudCenterPoint.y += plus;
        hud.animationBgView.center = hudCenterPoint;
    }
    
    [hud addSubview:hud.animationBgView];
    
    [hud beginAnimation];
    
    if (timeDelay>0)
    {
        [hud performSelector:@selector(hide) withObject:nil afterDelay:timeDelay];
    }
    return hud;
}

+ (void)hideHudForView:(UIView *)view
{
    
    UIView *currentView = view;
    if (!currentView)
    {
        currentView = [[UIApplication sharedApplication].windows lastObject];
    }
    CustomLoadingView *currentHud = nil;
    for (id obj in currentView.subviews)
    {
        if ([obj isKindOfClass:self])
        {
            CustomLoadingView *hud = (CustomLoadingView *)obj;
            currentHud = hud;
            [hud hide];
            break;
        }
    }
    if (!currentHud&&!view&&[UIApplication sharedApplication].windows.count>=2)
    {
        [self hideHudForView:[[UIApplication sharedApplication].windows objectAtIndex:[UIApplication sharedApplication].windows.count-2]];
        if ([UIApplication sharedApplication].windows.count>=3)
        {
            [self hideHudForView:[[UIApplication sharedApplication].windows objectAtIndex:[UIApplication sharedApplication].windows.count-3]];
        }
    }
}

- (void)beginAnimation
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    animation.duration = 1.8;
    animation.repeatCount = HUGE;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    
    animation.toValue = [NSNumber numberWithFloat:(2 * M_PI)];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;

    [self.yuanview.layer addAnimation:animation forKey:@"animationtransform"];
}

- (void)hide
{
    [self.yuanview.layer removeAnimationForKey:@"animationtransform"];
    [self.yuanview removeFromSuperview];
    [self.animationBgView removeFromSuperview];
    [self removeFromSuperview];
}
 */


+ (CustomLoadingView *)showHudToView:(UIView *)view
{
    return [self showHudToView:view afterDelay:-1];
}
+ (CustomLoadingView *)showHudToView:(UIView *)view afterDelay:(NSTimeInterval)timeDelay
{
    return [self showRealHudToView:view afterDelay:timeDelay];
}

+ (CustomLoadingView *)showRealHudToView:(UIView *)view afterDelay:(NSTimeInterval)timeDelay
{
    [self hideHudForView:view];
    
    if (!view)
    {
        view = [[UIApplication sharedApplication].windows lastObject];
    }
    
    //    view = [[UIApplication sharedApplication].windows lastObject];
    
    NSLog(@"loadingView*************%@",NSStringFromCGRect(view.bounds));
    
    for (id obj in view.subviews)
    {
        if ([obj isKindOfClass:[UITableView class]]||[obj isKindOfClass:[UIScrollView class]])
        {
            UIScrollView *tableView = (UIScrollView *)obj;
            if (tableView.contentInset.top>10)
            {
                return nil;
            }
            else
            {
                if (tableView.contentInset.bottom > 10)
                {
                    if (tableView.contentOffset.y>0)
                    {
                        return nil;
                    }
                    else
                    {
                        
                    }
                }
                else
                {
                    //                    return nil;
                }
            }
        }
    }
    
    CustomLoadingView *hud = [[CustomLoadingView alloc]initWithFrame:view.bounds];
    hud.backgroundColor = [UIColor clearColor];
    [view addSubview:hud];
    [view bringSubviewToFront:hud];
    

//    [[NSNotificationCenter defaultCenter]addObserverForName:@"Notification_ViewWillDisapper" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
//        @try {
//            [hud.superview removeObserver:hud forKeyPath:@"frame"];
//        }
//        @catch (NSException *exception) {
//            return;
//        }
//    }];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:@"Notification_ViewWillDisapper" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [hud hide];
    }];
    
    [[NSNotificationCenter defaultCenter]addObserverForName:@"Notification_ViewDidLayoutSubviews" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (hud.superview != [UIApplication sharedApplication].keyWindow)
        {
            hud.frame = hud.superview.bounds;
            hud.animationIV.center = hud.center;
        }
    }];
    
//    [hud.superview addObserver:hud forKeyPath:@"frame" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    UIImageView *animationIV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"loading_1"]];
    animationIV.center = hud.center;
    
//    NSLog(@"loadingView*************%@",NSStringFromCGPoint(animationIV.center));
//    
//    CGFloat plus = [UIScreen mainScreen].bounds.size.height/2 - hud.superview.height/2;
//    animationIV.center = CGPointMake(hud.center.x, hud.center.y-plus);
//    hud.orginPoint = animationIV.center;
//    
//    if (view != [UIApplication sharedApplication].keyWindow)
//    {
//        if (view.height==SCREEN_HEIGHT)
//        {
//            animationIV.center = CGPointMake(hud.center.x, hud.center.y-64);
//        }
//    }
//    
//    NSLog(@"loadingView*************1%@",NSStringFromCGPoint(animationIV.center));
    
    
    
    
    NSMutableArray *imageAry = [NSMutableArray arrayWithCapacity:24];
    float timeInterval = 0.72;
    for (int i=1;i<24;i++)
    {
        UIImage *aImage = [UIImage imageNamed:[NSString stringWithFormat:@"loading_%d",i]];
        [imageAry addObject:aImage];
    }
    [animationIV setAnimationImages:imageAry];
    [animationIV setAnimationDuration:timeInterval];
    [animationIV setAnimationRepeatCount:HUGE_VAL];
    
    [hud addSubview:animationIV];
    hud.animationIV = animationIV;
    
    
//    CGPoint centerPoint = [hud convertPoint:hud.center toView:[UIApplication sharedApplication].keyWindow];
//    if (centerPoint.y != [UIScreen mainScreen].bounds.size.height/2)
//    {
//        CGFloat plus = [UIScreen mainScreen].bounds.size.height/2 - centerPoint.y;
//        CGPoint hudCenterPoint = hud.animationIV.center;
//        hudCenterPoint.y += plus;
//        hud.animationIV.center = hudCenterPoint;
//    }
    
    
    [animationIV startAnimating];
    
    if (timeDelay>0)
    {
        [hud performSelector:@selector(hide) withObject:nil afterDelay:timeDelay];
    }
    
    
    [[NSNotificationCenter defaultCenter]addObserverForName:UIApplicationWillTerminateNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        [hud hide];
         }];
    [[NSNotificationCenter defaultCenter]addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
            [hud hide];
             }];
    
    return hud;
    
}

+ (void)hideHudForView:(UIView *)view
{
    [self hideRealHudForView:view];
}

+ (void)hideRealHudForView:(UIView *)view
{
    UIView *currentView = view;
    if (!currentView)
    {
        currentView = [[UIApplication sharedApplication].windows lastObject];
    }
    CustomLoadingView *currentHud = nil;
    for (id obj in currentView.subviews)
    {
        if ([obj isKindOfClass:[self class]])
        {
            CustomLoadingView *hud = (CustomLoadingView *)obj;
            currentHud = hud;
            [hud hide];
            break;
        }
    }
    if (!currentHud&&!view&&[UIApplication sharedApplication].windows.count>=2)
    {
        [self hideHudForView:[[UIApplication sharedApplication].windows objectAtIndex:[UIApplication sharedApplication].windows.count-2]];
        if ([UIApplication sharedApplication].windows.count>=3)
        {
            [self hideHudForView:[[UIApplication sharedApplication].windows objectAtIndex:[UIApplication sharedApplication].windows.count-3]];
        }
    }
}

- (void)hide
{
    [self.animationIV stopAnimating];
    [self.animationIV removeFromSuperview];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self removeFromSuperview];
//    @try {
//        [self.superview removeObserver:self forKeyPath:@"frame"];
//    }
//    @catch (NSException *exception) {
//        return;
//    }
//    @finally
//    {
//        [self removeFromSuperview];
//    }
//    
    
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    CustomLoadingView *hud = self;
    // 这个就算看不见也需要处理
    if ([keyPath isEqualToString:@"frame"])
    {
        
//        hud.animationIV.center = hud.center;
        
        NSLog(@"total:%@---%@",NSStringFromCGRect([UIScreen mainScreen].bounds),NSStringFromCGRect(hud.superview.frame));
        
        CGFloat plus = [UIScreen mainScreen].bounds.size.height/2 - hud.superview.height/2;
        
        NSLog(@"plus:%f",plus);
        
        if (plus)
        {
            CGPoint hudCenterPoint = hud.animationIV.center;
            if (hudCenterPoint.y==hud.orginPoint.y - plus)
            {
                
            }
            else
            {
                hudCenterPoint.y -= plus;
                hud.animationIV.center = hudCenterPoint;
            }
            
        }
        
        hud.bounds = hud.superview.bounds;

        
    }
    
    return;
}




@end
